package com.fqyd.campustransaction.controller;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.fqyd.campustransaction.model.User;
import com.fqyd.campustransaction.utils.Tools;

/**
 * 登录 / 注册
 */
@Controller
@Scope(value = "prototype")
public class LoginController extends BaseController {

	@RequestMapping("login")
	public String login(HttpServletRequest request) {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		if (Tools.isEmpty(username)) {
			return "login";
		}
		User user = userService.login(username, password);
		if (user == null) {
			request.setAttribute("username", username);
			request.setAttribute("message", "学号或密码错误");
			return "login";
		}
		HttpSession session = request.getSession();
		session.setAttribute("loguser", user);
		return "redirect:index.do";
	}

	@RequestMapping("admin_login")
	public String adminLogin(HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute("loguser");
		if (user == null) {
			String username = request.getParameter("username");
			String password = request.getParameter("password");
			if (Tools.isEmpty(username)) {
				return "admin/login";
			}
			user = userService.login(username, password);
			if (user == null) {
				request.setAttribute("username", username);
				request.setAttribute("message", "用户名或密码错误");
				return "admin/login";
			}
			HttpSession session = request.getSession();
			session.setAttribute("loguser", user);
			return "redirect:admin_index.do";
		}
		user = userService.getById(user.getId());
		if (user == null) {
			return "admin/login";
		}
		return "redirect:admin_index.do";
	}

	@RequestMapping("register")
	public String register(HttpServletRequest request, RedirectAttributes attributes) {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		if (Tools.isEmpty(username) || Tools.isEmpty(password)) {
			return "register";
		}
		User user = new User();
		user.setId(Tools.createID());
		user.setUsername(username);
		user.setPassword(password);
		user.setRole("普通学生");
		user.setCreateTime(new Date());
		if (userService.checkUsername(username)) {
			request.setAttribute("username", username);
			request.setAttribute("message", "学号已存在");
			return "register";
		}
		userService.add(user);
		attributes.addFlashAttribute("message", "注册成功，马上登录");
		return "redirect:login.do";
	}

	@RequestMapping("logout")
	public String logout(HttpSession session, RedirectAttributes attributes) {
		session.removeAttribute("loguser");
		attributes.addFlashAttribute("message", "您已成功退出登录！");
		return "redirect:index.do";
	}
}
